//
//  HomeViewModel.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/1/31.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
class HomeViewModel {
    
    var requestUrl:String
    
    var parameters:[String: Any]?
    
    var isLoadMore: Bool = false
    
    private var models: [ConsultaionModel] = Array()
    
    init(requestUrl:String, parameters:[String: Any]?) {
        self.requestUrl = requestUrl
        self.parameters = parameters
    }
    
    func requestData(isLoadMore:Bool, complete: @escaping ([ConsultaionModel], Bool) -> Void, errorRequest:@escaping (FailureJSONResponse, Bool) -> Void) {
        func analysisData(_ json: [String: Any]) -> ([ConsultaionModel]){
            if !isLoadMore {
                models.removeAll()
            }
            
            let data = json["data"] as? Array<[String: Any]>
            if let datas = data {
                self.isLoadMore = datas.count == MAXRequestCount
                for item in datas {
                    let model = ConsultaionModel(item)
                    models.append(model)
                }
            }
            return (models)
        }
        
        let netWorking = Networking(baseURL: BaseURL)
        netWorking.post(requestUrl, parameters:parameters) {  result in
            switch result {
            case .success(let response):
                let json = response.dictionaryBody
                complete(analysisData(json), self.isLoadMore)
            case .failure(let response):
                errorRequest(response, self.isLoadMore)
            }
        }
    }
}
